/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * <p>CreateTime: 2006-3-27 </p>
 * @author pengz
 * @version 1.0
 */

package cn.agiledata.bank.myspace.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.agiledata.bank.account.util.AccountHistoryObserverInter;
import cn.agiledata.bank.audit.form.AuditGroupBean;
import cn.agiledata.bank.audit.form.AuditStepBean;
import cn.agiledata.bank.common.dao.AccountTemplateInter;
import cn.agiledata.bank.common.dao.BankTemplate;
import cn.agiledata.bank.common.dao.TransactionTemplate;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.PageBean;
import cn.agiledata.bank.common.util.StringUtil;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.AccountBank;
import cn.agiledata.bank.hibernateBean.AccountGroups;
import cn.agiledata.bank.hibernateBean.AccountHis;
import cn.agiledata.bank.hibernateBean.AccountLimit;
import cn.agiledata.bank.hibernateBean.Acctlimithis;
import cn.agiledata.bank.hibernateBean.ActionType;
import cn.agiledata.bank.hibernateBean.Authentication;
import cn.agiledata.bank.hibernateBean.BankInfo;
import cn.agiledata.bank.hibernateBean.GradeRules;
import cn.agiledata.bank.hibernateBean.Groups;
import cn.agiledata.bank.hibernateBean.OperSubacct;
import cn.agiledata.bank.hibernateBean.Operator;
import cn.agiledata.bank.hibernateBean.SubAccount;
import cn.agiledata.bank.hibernateBean.Transaction;
import cn.agiledata.bank.myspace.bean.AccountHisQueryDetailBean;
import cn.agiledata.bank.myspace.bean.AuthenticationBean;
import cn.agiledata.bank.myspace.bean.PaperBean;
import cn.agiledata.bank.myspace.dao.IMySpaceDao;
import com.vnv.infrastructure.logic.IPBAppFactory;

public class MySpaceServiceImpl implements IMySpaceService {

	private TransactionTemplate tt;

	private AccountTemplateInter at;

	private BankTemplate bt;
	
	private ISendMailService sendMail;
	
	private IMySpaceDao mySpaceDao;
	
	private AccountHistoryObserverInter ahoi;

	// 属性，得到log
	protected final Log log = LogFactory.getLog(getClass());
	
    private AuthenticateService getAuthenticateService(){
        return (AuthenticateService) IPBAppFactory.getObj("authenticateService");
    }

	Account account;

	int LOGINPASS_NOT = 0;

	public Account getAccount(String id) {
		return at.getAccount(id);
	}

	public Transaction getTransaction(String id) {
		return tt.getTransaction(id);
	}

	// mail
	public int updateMail(Map map) {
		String accountID = null;
		Account account = this.getAccount(accountID);
		String email = null;
		if (map.get("mail") != null)
			email = (String) map.get("mail");
		else
			return 1;
		account.setEmail(email);
		this.updateAccount(account);
		
		return LOGINPASS_NOT;
	}
	
	public void sendRegisterActivate(String accountID){
		sendMail.sendRegisterActivateReport(accountID);
	}

	public final int OLDPASS_WRONG = 10;

	public int updateAccountBank(Map map) {

		return LOGINPASS_NOT;
	}

	public int updateLoginPass(Map map) {

		return LOGINPASS_NOT;
	}

	public int updatePayPass(Map map) {
		return LOGINPASS_NOT;
	}

	public boolean updateAccount(Account account) {
		return at.updateAccount(account);
	}

	public BankInfo getBankInfo(String bID) {
		return bt.getBankInfo(bID);
	}

	public AccountBank getAccountBank(String abid) {
		return at.getAccountBank(abid);
	}


	public void updateAccountBank(AccountBank ab) {
		bt.updateAccountBank(ab);
	}
	
//根据银行卡号码和账户ID检查是否唯一
	public boolean isUniqueAccountBank(String accountId, Long accountSeq, Long id) {
		return at.isUniqueAccountBank(accountId, accountSeq, id);
	}
	
	//根据银行卡别名和账户ID检查是否唯一
	public boolean isUniqueAccountAlias(String bankAlias, Long accountSeq, Long id) {
		return at.isUniqueAccountAlias(bankAlias, accountSeq, id);
	}

	public void delAccountBank(String aBankID) {
		AccountBank aBank = getAccountBank(aBankID);
//		if (aBankID != null)
		if (aBank == null)
			return;
		aBank.setIsValid("N");
		if("Y".equals(aBank.getDefaultFlag())) {
			aBank.setDefaultFlag("N");
		}
		bt.updateAccountBank(aBank);
	}

	public void updateBankSetDefault(String aBankID) {
		AccountBank aBank = getAccountBank(aBankID);
		if (aBank == null)
			return;
		Iterator iAbanks = aBank.getAccount().getAccountBanks().iterator();
		while (iAbanks.hasNext()) {
			AccountBank abank = (AccountBank) iAbanks.next();
			abank.setDefaultFlag("N");
			bt.updateAccountBank(abank);
		}
		aBank.setDefaultFlag("Y");
		bt.updateAccountBank(aBank);

	}

	public void RecommedFrends(String AccountID) {
	}

	public int accountHisQueryCount(Map parameter) {
		return at.getAccountHisCount(parameter);
	}

	public List accountQueryList(Map parameter, int pageNo, int recordPerPage) {
		return at.getAccountHisQueryList(parameter, pageNo, recordPerPage);
	}

	public List accountHisQueryList(Map parameter, int pageNo, int recordPerPage) {
		return at.getAccountHisQueryList(parameter, pageNo, recordPerPage);
	}
	
	public PageBean getAccountHisListPageBean(Map param, int pageNo, int recordPerPage) {
		return at.getAccountHisListPageBean(param,pageNo,recordPerPage); 
	}
	
	public AccountHisQueryDetailBean accountHisQueryDetail(String tid,String aid) {
		return at.getAccountHisQueryDetail(tid,aid); 
	}
	
	public PaperBean getPaper(String tid,String aid) {
		return at.getPaper(tid,aid);
	}
	
	//根据操作者id得到操作者信息?
	public Operator getOperatorById(String id) {
		return mySpaceDao.getOperatorById(id);
	}
	
	//银行账户信息
	public List getAccountBankList(String accountID) {
		return mySpaceDao.getAccountBankList(accountID);
	}
	
	//预设交易对象列表
	public List getTrxObjectList(String accountID) {
		return mySpaceDao.getTrxObjectList(accountID);
	}
	//修改操作者
	public void updateOperator(Operator oper) {
		mySpaceDao.updateOperator(oper);
	}


	public void setAt(AccountTemplateInter at) {
		this.at = at;
	}

	public void setTt(TransactionTemplate tt) {
		this.tt = tt;
	}

	public void setBt(BankTemplate bt) {
		this.bt = bt;
	}

	public ISendMailService getSendMail() {
		return sendMail;
	}

	public void setSendMail(ISendMailService sendMail) {
		this.sendMail = sendMail;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	public void setMySpaceDao(IMySpaceDao mySpaceDao) {
		this.mySpaceDao = mySpaceDao;
	}

	public boolean isUniqueSubAccountField(String value, String dbName, String createUser) {
		if(StringUtil.isStrEmpty(value)){
			return true;
		}
		return mySpaceDao.isUniqueSubAccountField(value,dbName,createUser);
	}

	public boolean isUniqueSubAccountFieldExcludeOwn(String value, String dbName, String id, String createUser) {
		if(StringUtil.isStrEmpty(value)){
			return true;
		}
		return mySpaceDao.isUniqueSubAccountFieldExcludeOwn(value,dbName,new Long(id),createUser);
	}
	
	public void saveOrUpdateAccount
	(Account acc,InputStream photoStream,InputStream cardPhotoStream)throws Exception {
		at.saveOrUpdateAccount(acc,photoStream,cardPhotoStream,null);
	}

	public void delPeerAccount(String acctID) {
		if (acctID != null)
			at.removePeerAccount(acctID);
		
	}

	public PageBean getAcctSubHisPageBean(Map param, int pageNo, int recordPerPage) {
		return at.getAcctBalHisPageBean(param,pageNo,recordPerPage);
	}

	public void saveAcctHis(AccountHis acctHis) {
		at.saveAcctHis(acctHis);
	}

	public List getSubAccountList(String id) {
	    return	at.getAllSubAccountsByMainId(id);
	
	}

	public void updateSubAccount(SubAccount sub) {
		
		at.updateSubAccount(sub);
	}

	public void updateAcctLimit(AccountLimit al){
		mySpaceDao.updateAcctLimit(al);
	}
	public void saveAcctLimit(AccountLimit al){
		mySpaceDao.saveAcctLimit(al);
	}
	public AccountLimit getAcctlimitByAcctGrading(Account account){
		return mySpaceDao.getAcctlimitByAcctGrading(
				getGroupByAccount(account, Constant.GROUP_TYPE_D).getId().toString());
	}
	public AccountLimit getAcctlimitByAcctId(String id){
		return mySpaceDao.getAcctlimitByAcctId(id);
	}
	public void setSumAmmount(){
		mySpaceDao.updateAllAccount();
	}

	public void saveAcctLimitHis(Acctlimithis als) {
		 mySpaceDao.saveAcctLimithis(als);
		
	}
	/***
	 * 根据account返回用户等级的升级规则
	 */
	public GradeRules getGradingRulesByGrading(Account account) {
		return mySpaceDao.getGradingRulesByGrading(
				getGroupByAccount(account, Constant.GROUP_TYPE_C).getId().toString());
	}
	
	
	
	/***
	 * 返回Groups对象
	 * @param acc
	 * @param type
	 * @return Groups
	 */
	public Groups getGroupByAccount(Account acc,String type){
		Set set = acc.getAccountGroupses();
		Groups group = new Groups();
		for (Iterator iter = set.iterator(); iter.hasNext();) {
			AccountGroups ag = (AccountGroups) iter.next();
			if (ag.getGroups().getGroupType().equals(type)) 
				group = ag.getGroups();
		}
		return group;
	}
	
	public Set getAccountGroupsSet(Account acc,String groupType,Groups group){
		AccountGroups accountGroup = new AccountGroups();
		AccountGroups limitAccountGroup = new AccountGroups();
		Set set = new HashSet();
		for (Iterator iter = acc.getAccountGroupses().iterator(); iter.hasNext();) {
			AccountGroups accGroup	= (AccountGroups) iter.next();
			if (accGroup.getGroups().getGroupType().equals(groupType)) {
				accountGroup = accGroup;
			}
			if (Constant.GROUP_TYPE_D.equals(accGroup.getGroups().getGroupType()))
				limitAccountGroup = accGroup;
		}
		accountGroup.setGroups(group);
		Groups limitGroup = getGroupByAccount(acc, Constant.GROUP_TYPE_D);
		limitGroup = getNextLimit(limitGroup.getId().toString());
		ahoi.updateAccountGroupHis(accountGroup);
		limitGroup.getId();
		limitAccountGroup.setGroups(limitGroup);
		ahoi.updateAccountGroupHis(limitAccountGroup);
		set.add(accountGroup);
		set.add(limitAccountGroup);
		return set;
	}
	
	public List getAuthenticationById(String id){
		return mySpaceDao.getAuthenticationById(id);
	}

	public List getAuthenticationMethod() {
		
		return mySpaceDao.getAuthenticationMethod();
	}
	public void setList(List allList,List must,List notMust){
		Iterator it = allList.iterator();
		while(it.hasNext()){
		Authentication authentication = (Authentication)it.next();
		
		if(authentication.getOptionType().equals(Constant.MUSTOPTION)){
			must.add(authentication);
		}
		if(authentication.getOptionType().equals(Constant.NOTMUSTOPTION)){
			notMust.add(authentication);
		}
		}
	}
	/**
	 * 验证是否通过*/
	public List authenticat(List authenticationList,Account account){
		String ifAccess = "N";
		List list = new ArrayList();
		Iterator it = authenticationList.iterator();
		
		while(it.hasNext()){
		    	AuthenticationBean bean = new AuthenticationBean();
				Authentication authentication = (Authentication)it.next();
				bean.setAuthentication(authentication);
				int type = new Integer(authentication.getAuthenticationMethod()).intValue();
				boolean ifBank =getAuthenticateService().feasibleBankCardAuthentication(account);
				boolean ifMobileNotPass = getAuthenticateService().getMobileTelAuthenticationStatus(account).equals(Constant.AUTHENTICATION_STATUS_UNPASS);
				boolean ifCardPass = getAuthenticateService().getIdcardAuthenticationStatus(account).equals(Constant.AUTHENTICATION_STATUS_PASS);
				switch (type){
				case 1: 
					if(ifBank){
						ifAccess = "Y";
					}else{
						ifAccess = "N";
						}	
	            bean.setIfAccess(ifAccess);
	            list.add(bean);
	            continue;
				case 2:
					if(ifMobileNotPass){
						ifAccess = "N";
						
					}else{
						ifAccess = "Y";
						}
					
					 bean.setIfAccess(ifAccess);
					 list.add(bean);
			            continue;	
				case 3:
				    if(ifCardPass){
				    
				    	ifAccess = "Y";
				    	 
				    }else{
				    	ifAccess = "N";
				    	}
				    bean.setIfAccess(ifAccess);
				    list.add(bean);
		            continue;
				}	
				
			}
		return list;
	}
	 /*
	  * 查询客户3种认证的通过情况**/
	public void ifAccess(HttpServletRequest request,Account account){
		String ifBank;
		if(getAuthenticateService().feasibleBankCardAuthentication(account)){
			ifBank = "Y";
		}else{ifBank = "N";}
		
		String ifMobile;
		if(getAuthenticateService().getMobileTelAuthenticationStatus(account).equals(Constant.AUTHENTICATION_STATUS_UNPASS)){
			ifMobile = "N";
		}else{ifMobile = "Y";}
		String ifCard;
		if(getAuthenticateService().getIdcardAuthenticationStatus(account).equals(Constant.AUTHENTICATION_STATUS_PASS)){
			ifCard = "Y";
		}else if(getAuthenticateService().getIdcardAuthenticationStatus(account).equals(Constant.AUTHENTICATION_STATUS_SUBMITTED)){
			ifCard = "W";//W代表身份证认证在等待审核状态
		}else{
			ifCard="N";
			}
		request.setAttribute("ifBank",ifBank);
		request.setAttribute("ifMobile", ifMobile);
		request.setAttribute("ifCard", ifCard);
	}

	public void setAhoi(AccountHistoryObserverInter ahoi) {
		this.ahoi = ahoi;
	}

	public Groups getNextLimit(String id) {
		String groupId;
		if (Constant.LIMIT_GRADING_A.equals(id)) {
			groupId = Constant.NEXT_A;
		} else if (Constant.LIMIT_GRADING_B.equals(id)) {
			groupId = Constant.NEXT_B;
		} else {
			groupId = Constant.NEXT_C;
		}
		Groups groups = mySpaceDao.getGroupsById(groupId);
		return groups;
	}
	
	public boolean hasOperators(String accountId) {
		List list = mySpaceDao.getAuditOperater(accountId);
		if(list.size()>0)
			return true;
		else
			return false;
	}

	public boolean hasAuditGroup(String accountId) {
		List list = mySpaceDao.getAuditGroup(accountId);
		if(list.size()>0)
			return true;
		else
			return false;
	}

	public boolean ifCouldPay(String opId, String subId) {
		OperSubacct os = mySpaceDao.getOperSubacct(opId, subId);
		if (os == null) {
			return false;
		} else {
			return true;
		}
	}

	public ActionType getActionTypeById(String id) {
		return mySpaceDao.getActionTypeById(id);
	}

	public List getAuditOper(String accountId) {
		return mySpaceDao.getAuditOperaters(accountId);
	}

	public List getAuditStepList(List auditOperList,int size){
		List auditStepList =new ArrayList();
		List auditGroupList = new ArrayList();
		Iterator it = auditOperList.iterator();
		
		while(it.hasNext()){
			Operator oper = (Operator)it.next();
			AuditGroupBean groupbean =new AuditGroupBean(false,oper);
			auditGroupList.add(groupbean);
		}
		for(int i=0;i<size;i++){
			String name = new String();
			AuditStepBean stepBean = new AuditStepBean();
			switch (i)
			{
				case 0:
					if(size==1)
						name=Constant.AUDIT_FINAL_STEP;
					else
						name=Constant.AUDIT_FIRST_STEP;
					break;
				case 1:
					if(size==2)
						name=Constant.AUDIT_FINAL_STEP;
					else
						name=Constant.AUDIT_SECOND_STEP;
					break;
				case 2:
					if(size==3)
						name=Constant.AUDIT_FINAL_STEP;
					else
						name=Constant.AUDIT_THIRD_STEP;
					break;
				case 3:
					if(size==4)
						name=Constant.AUDIT_FINAL_STEP;
					else
						name=Constant.AUDIT_FORTH_STEP;
					break;
				case 4:
					if(size==4)
						name=Constant.AUDIT_FINAL_STEP;
					else
						name=Constant.AUDIT_FIFTH_STEP;
					break;
				case 5:
						name=Constant.AUDIT_FINAL_STEP;
			}
			stepBean.setId(i);
			stepBean.setName(name);
			stepBean.setAuditGroupBean(auditGroupList);
			auditStepList.add(stepBean);
		}
		return auditStepList;
	}
	
	public boolean ifOperUsed(String operId){
		List list = mySpaceDao.getOper(operId, Constant.ES_TRANS_STATUS_FINISH);
		return list.size()>0;
	}

}